/* luhn.c - Luhn algorithm test program */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LEN 128

/* 函数原型 */
int CheckLuhn ( const char * cardId, int sum[2] );
int ReadLine(char *s);

int main()
{
    int s[2]={0}, r;
    char id[MAX_LEN];

    while (ReadLine(id) > 0) {
        r = CheckLuhn(id, s);
        printf("%s,R=%d\t%d\t%d\n", id, r, s[0], s[1]);
    }
    return 0;
}

/* 字符串读取 */
int ReadLine(char *s)
{
    int n = 0, ch = 0;
    while((ch = getchar()) != '\n' && ch != EOF && n <= MAX_LEN - 1)
        s[n++] = ch;
    s[n]='\0';
    return n;
}

/* Luhn模10校验 */
int CheckLuhn ( const char * cardId, int sum[2] )
{
    int i, k, ch, num, even_flag, len;

    len = strlen(cardId);
    k = 0;
    even_flag = 0;

    /* 累加器清0(非常重要) */
    sum[0] = 0;
    sum[1] = 0;

    /* 反向遍历 */
    for (i = len - 1; i >= 0; --i)
    {
        ch = cardId[i];
        /* 提取数字 */
        num = (ch >= '0' && ch <= '9') ? ch - '0' : 0;
        if (even_flag) /* 偶数位 */
        {
            num += num;
            if (num > 9) num = (num % 10) + 1;
            sum[1] += num;
        }
        else            /* 奇数位 */
        {
            sum[0] += num;
        }

        /* 奇偶状态切换 */
        even_flag++;
        even_flag &= 1;
    }

    /* 判断并返回 */
    k = sum[0] + sum[1];

    return (k % 10) ? 1 : 0;
}

